//
//  CZStatusOriginalView.swift
//  CZ29VVeibo
//
//  Created by apple on 16/6/27.
//  Copyright © 2016年 apple. All rights reserved.
//

import UIKit
// 纪录约束需要重写导入SnapKit
import SnapKit
class CZStatusOriginalView: UIView {
    // 声明一个全局的原创微博底部约束的供我们卸载
    var originalViewBottomConstraint: Constraint?
    // 供外界设置数据
    var status: CZStatus? {
        didSet{
            // 用户昵称
            nameLabel.text = status?.user?.name
            // 用户头像
            headImageView.sd_setImageWithURL(NSURL(string: status?.user?.profile_image_url ?? ""), placeholderImage: UIImage(named: "avatar_default_big"))
            // 时间// getWbTimeStr(status?.created_at ?? "")
            timeLabel.text = status?.createAtStr
            // 来源
            sourceLabel.attributedText = status?.sourceAttr
            // 微博内容
            contentLabel.attributedText = status?.textAttr
            
            // 认证图片
            vipImageView.image = status?.user?.verifiedImage
            // 会员等级
            expiredImageView.image = status?.user?.mbrankImage
            
            /*
                （考虑到cell的复用问题）
                01 先卸载原创微博的底部约束
                02 如果status?.pic_urls.count > 0 代表有配图
                        - 显示配图
                        - 要先赋值 然后进行约束
                        - 原创微博的底部 == 配图的底部 + 10（更新约束）
                反之 <= 0  均是没有配图
                        - 隐藏配图
                        - 原创微博的底部 == 微博正文的底部 + 10（更新约束）
            */
            //先卸载
            originalViewBottomConstraint?.uninstall()
            // 代表有配图
            if status?.pic_urls?.count > 0 {
                // 显示配图
                pictureView.hidden = false
                // 赋值
                pictureView.pic_urls = status?.pic_urls
                // 更新约束
                self.snp_makeConstraints { (make) -> Void in
                    originalViewBottomConstraint = make.bottom.equalTo(pictureView).offset(StautsMargin).constraint
                }
            }else {
                // 代表没有配图
                // 隐藏配图
                pictureView.hidden = true
                // 更新约束
                self.snp_makeConstraints { (make) -> Void in
                    originalViewBottomConstraint = make.bottom.equalTo(contentLabel).offset(StautsMargin).constraint
                }
            }
        }
    }
    
    /*
    
        aaa[马到成功]aaa  最终显示在cell上 aaa表情aaa
    
    
    
        aaaa[嘿嘿]bbbb[笑笑] range loc=4 len=4     笑笑  range  loc = 12  len 4
        正序行不同 //aaaa表bbbb[笑笑]
    
        倒序 aaaa[嘿嘿]bbbb表
    */
    func getWeiBoAttr(text: String) -> NSMutableAttributedString{
        // 富文本
        let resultAttr = NSMutableAttributedString(string: text)
        // 定义一个保存模型的数组
        var matchArray:[CZMatchResult] = [CZMatchResult]()
        
        // 正则匹配格式
        // 通过正则匹配结果
        (text as NSString).enumerateStringsMatchedByRegex("\\[[a-zA-Z0-9\\u4e00-\\u9fa5]+\\]") { (count, string, range, _) -> Void in
            // 转模型保存数组
            let matchRes = CZMatchResult(string: (string.memory as! String), range: range.memory)
            // 保存数据
            matchArray.append(matchRes)

        }

        // 倒序遍历
        for match in matchArray.reverse() {
            let emoticon = CZEmoticonTools.sharedTools.getSearchEmoticon(match.string)
            // 文本附件
            let att = NSTextAttachment()
            let path = emoticon?.path ?? ""
            let png = emoticon?.png ?? ""
            let name = path + png
            // 设置image
            att.image = UIImage(named: name, inBundle: CZEmoticonTools.sharedTools.emoticonBundle, compatibleWithTraitCollection: nil)
            // 行高
            let lineHeight = UIFont.systemFontOfSize(15).lineHeight
            // 设置bounds
            att.bounds = CGRect(x: 0, y: -4, width: lineHeight, height: lineHeight)
            
            let attr = NSAttributedString(attachment: att)
            resultAttr.replaceCharactersInRange(match.range, withAttributedString: attr)
        }

//        // 通过正则分割结果
//        (text as NSString).enumerateStringsSeparatedByRegex("\\[[a-zA-Z0-9\\u4e00-\\u9fa5]+\\]") { (count, string, range, _) -> Void in
//            print(string.memory)
//        }
        return resultAttr
    }
    
    
    // 处理微博来源字符串
    func getSourceStr(source: String?) -> NSMutableAttributedString{
        // 判断可选值是否有值 而且是否包含"> 字符串
        guard let s = source where s.containsString("\">")  else {
            let r = "来自 那遥远的地方"
            return getSourceAttr(r)
        }
        // 字符串的截取
        let start = s.rangeOfString("\">")!
        let end = s.rangeOfString("</a")!
        // 字符串截取
        let result = s.substringWithRange(start.endIndex..<end.startIndex)
        // 完成字符串拼接
        let r = "来自 \(result)"
        return getSourceAttr(r)
    }
    // 通过字符串生成富文本
    func getSourceAttr(result: String) -> NSMutableAttributedString{
        // 实例化一个富文本
        let attr = NSMutableAttributedString(string: result)
        // 获取range
        let range = (result as NSString).rangeOfString("来自")
        // 设置属性
        attr.addAttributes([NSForegroundColorAttributeName: ThemeColor], range: range)
        return attr
    }
    

    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK: - 设置视图
    private func setupUI(){
        backgroundColor = UIColor.whiteColor()
        // 01- 添加控件
        addSubview(headImageView)
        addSubview(nameLabel)
        addSubview(expiredImageView)
        addSubview(timeLabel)
        addSubview(sourceLabel)
        addSubview(vipImageView)
        addSubview(contentLabel)
        addSubview(pictureView)
        // 02 -添加约束
        // 头像
        headImageView.snp_makeConstraints { (make) -> Void in
            make.leading.top.equalTo(self).offset(StautsMargin)
            make.size.equalTo(CGSize(width: 35, height: 35))
        }
        // 昵称
        nameLabel.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(headImageView)
            make.leading.equalTo(headImageView.snp_trailing).offset(StautsMargin)
        }
        // 用户等级
        expiredImageView.snp_makeConstraints { (make) -> Void in
            make.leading.equalTo(nameLabel.snp_trailing).offset(StautsMargin)
            make.centerY.equalTo(nameLabel)
        }
        // 发布时间
        timeLabel.snp_makeConstraints { (make) -> Void in
            make.leading.equalTo(nameLabel)
            make.bottom.equalTo(headImageView)
        }
        // 来自
        sourceLabel.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(timeLabel)
            make.leading.equalTo(timeLabel.snp_trailing).offset(StautsMargin)
        }
        // 认证
        vipImageView.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(headImageView.snp_trailing)
            make.centerY.equalTo(headImageView.snp_bottom)
        }
        // 微博内容
        contentLabel.snp_makeConstraints { (make) -> Void in
            make.leading.equalTo(headImageView)
            make.top.equalTo(headImageView.snp_bottom).offset(StautsMargin)
        }
        // 原创微博配图
        pictureView.snp_makeConstraints { (make) -> Void in
           // make.size.equalTo(CGSize(width: 100, height: 100))
            make.leading.equalTo(contentLabel)
            make.top.equalTo(contentLabel.snp_bottom).offset(StautsMargin)
        }
        
        // 原创微博
        self.snp_makeConstraints { (make) -> Void in
            originalViewBottomConstraint = make.bottom.equalTo(pictureView).offset(StautsMargin).constraint
        }
        
        

        
    }
    
    // MARK: - 懒加载控件
    // 头像
    private lazy var headImageView: UIImageView = UIImageView(imgName: "avatar_default_big")
    // 用户昵称
    private lazy var nameLabel: UILabel = UILabel(textColor: UIColor.darkGrayColor(), textFont: 15)
    // 用户等级common_icon_membership_expired
    private lazy var expiredImageView: UIImageView = UIImageView(imgName: "common_icon_membership_expired")
    // 发布微博事件
    private lazy var timeLabel: UILabel = UILabel(textColor: ThemeColor, textFont: 10)
    // 来源
    private lazy var sourceLabel: UILabel = UILabel(textColor: UIColor.grayColor(), textFont: 10)
    // VIP
    private lazy var vipImageView: UIImageView = UIImageView(imgName: "avatar_vgirl")
    // 微博内容//UILabel(textColor: UIColor.blackColor(), textFont: 15)
    private lazy var contentLabel: UILabel = UILabel(textColor: UIColor.blackColor(), textFont: 15, maxWidth: SCREENW - 2*StautsMargin)
    // 原创微博配图
    private lazy var pictureView: CZPictureView = CZPictureView()
}

extension CZStatusOriginalView {
    ///// 会员等级 0-6
    //var mbrank: Int = 0
    func getMbrankImage(mbrank: Int) -> UIImage? {
        print("会员等级")
        // 如果会员等级 0-6 使用一下
        if mbrank > 0 && mbrank < 7 {
            return UIImage(named: "common_icon_membership_level\(mbrank)")
        }else {
            // 其他使用默认
            return UIImage(named: "common_icon_membership_expired")
        }
        
    }
    
    // 通过后台返回来的数据来判断/// 认证类型，-1：没有认证，0，认证用户，2,3,5: 企业认证，220: 达人
    func getVipImage(verified: Int) -> UIImage? {
        print("认证类型")
        switch verified{
        case 0:
            return UIImage(named: "avatar_vip")
        case 2,3,5:
            return UIImage(named: "avatar_enterprise_vip")
        case 220:
            return UIImage(named: "avatar_grassroot")
        default:
            return UIImage(named: "avatar_vgirl")
        }
    }
}



